// pages/supplier/form/form.js
const supplierApi = require('../../../api/supplier')
const fileApi = require('../../../api/file')

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isEdit: false,
		id: null,
		form: {
			supplierCode: '',
			supplierName: '',
			contactPerson: '',
			contactPhone: '',
			contactEmail: '',
			address: '',
			businessLicense: '',
			creditRating: '',
			status: 1,
			description: '',
			logoFileId: null,
			logoUrl: ''
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		if (options && options.id) {
			this.setData({ isEdit: true, id: Number(options.id) })
			this.loadDetail(Number(options.id))
		}
	},

	async loadDetail(id) {
		try {
			wx.showLoading({ title: '加载中' })
			const detail = await supplierApi.getSupplierById(id)
			const logoFile = detail.logoFile || null
			this.setData({
				form: {
					supplierCode: detail.supplierCode || '',
					supplierName: detail.supplierName || '',
					contactPerson: detail.contactPerson || '',
					contactPhone: detail.contactPhone || '',
					contactEmail: detail.contactEmail || '',
					address: detail.address || '',
					businessLicense: detail.businessLicense || '',
					creditRating: detail.creditRating || '',
					status: detail.status != null ? detail.status : 1,
					description: detail.description || '',
					logoFileId: (logoFile && logoFile.fileId) || detail.logoFileId || null,
					logoUrl: (logoFile && logoFile.accessUrl) || detail.logoUrl || ''
				}
			})
		} catch (e) {
			wx.showToast({ title: '加载失败', icon: 'none' })
		} finally {
			wx.hideLoading()
		}
	},

	// 选择并上传Logo
	chooseAndUploadLogo() {
		wx.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				try {
					wx.showLoading({ title: '上传中' })
					const tempFilePath = res.tempFilePaths[0]
					const uploadRes = await fileApi.uploadFile(tempFilePath)
					// uploadRes 已是后端 data，字段包含 fileId / accessUrl
					this.setData({
						'form.logoFileId': uploadRes.fileId || null,
						'form.logoUrl': uploadRes.accessUrl || ''
					})
					wx.showToast({ title: '上传成功', icon: 'success' })
				} catch (e) {
					wx.showToast({ title: '上传失败', icon: 'none' })
				} finally {
					wx.hideLoading()
				}
			}
		})
	},

	// 提交保存
	onSubmit() {
		const payload = { ...this.data.form }
		// 确保 logoFileId 为 null 或 数字，避免空字符串
		if (!payload.logoFileId) {
			payload.logoFileId = null
		}
		wx.showLoading({ title: '保存中' })
		const isEdit = this.data.isEdit
		const id = this.data.id
		const req = isEdit ? supplierApi.updateSupplier(id, payload) : supplierApi.createSupplier(payload)
		req.then(() => {
			wx.showToast({ title: '保存成功', icon: 'success' })
			setTimeout(() => {
				wx.navigateBack()
			}, 800)
		}).catch(err => {
			wx.showToast({ title: err.message || '保存失败', icon: 'none' })
		}).finally(() => wx.hideLoading())
	},

	/**
	 * 其余生命周期保持默认
	 */
	onReady() {},
	onShow() {},
	onHide() {},
	onUnload() {},
	onPullDownRefresh() {},
	onReachBottom() {},
	onShareAppMessage() {}
})